from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class LoginView(APIView):
    serializer_class = TokenObtainPairSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')

            if not username or not password:
                return Response({
                    'status': 'error',
                    'message': '请提供用户名和密码'
                }, status=status.HTTP_400_BAD_REQUEST)

            user = authenticate(request, username=username, password=password)

            if user is not None:
                # 认证成功，生成 Token
                serializer = self.serializer_class(data=request.data)
                serializer.is_valid(raise_exception=True)
                return Response({
                    'status': 'success',
                    'data': {
                        'token': serializer.validated_data['access'],
                        'user': user.username,
                    }
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    'status': 'error',
                    'message': '用户名或密码错误'
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            return Response({
                'status': 'error',
                'message': '服务器错误'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
